package com.hzcx.app.simplechat.ui.setting;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.ui.chat.event.ChatListRefreshEvent;
import com.hzcx.app.simplechat.ui.friend.event.AddFriendSuccessEvent;
import com.hzcx.app.simplechat.ui.friend.event.DeleteFriendEvent;
import com.hzcx.app.simplechat.ui.moment.event.MomentCreateEvent;
import com.hzcx.app.simplechat.ui.publicui.PublicConfirmDialog;
import com.hzcx.app.simplechat.ui.publicui.PublicRoundDialog;
import com.hzcx.app.simplechat.ui.publicui.interfaces.OnPublicMenuOnClickListener;
import com.hzcx.app.simplechat.ui.setting.bean.BatchClearListBean;
import com.hzcx.app.simplechat.ui.setting.contract.BatchClearContract;
import com.hzcx.app.simplechat.ui.setting.presenter.BatchClearPresenter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 批量清除
 */
public class BatchClearActivity extends BaseActivity<BatchClearPresenter> implements BatchClearContract.View {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;

    private int type = 1;
    private Thread thread;

    @Override
    public int getLayout() {
        return R.layout.activity_batch_clear;
    }

    @Override
    public void initPresenter() {
        mPresenter = new BatchClearPresenter();
    }

    @Override
    public void initView() {
        tvTitle.setText("批量清除");
    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.tv_clear_friend, R.id.tv_clear_chat, R.id.tv_chat_moment})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_clear_friend:
                type = 1;
                mPresenter.getBatchClearList(this, type);
                break;

            case R.id.tv_clear_chat:
                type = 2;
                mPresenter.getBatchClearList(this, type);
                break;

            case R.id.tv_chat_moment:
                type = 3;
                mPresenter.getBatchClearList(this, type);
                break;
        }
    }

    /**
     * 批量清除成功
     */
    @Override
    public void clearSuccess() {
        if (type == 1) {
            EventBus.getDefault().post(new MomentCreateEvent());
        }
        if (type == 3) {
            EventBus.getDefault().post(new AddFriendSuccessEvent());
        }
        showError("清除成功");
    }

    /**
     * 清除列表获取成功
     *
     * @param data
     */
    @Override
    public void clearListResult(List<BatchClearListBean> data) {
        try {
            List<String> list = new ArrayList<>();
            for (BatchClearListBean bean : data) {
                list.add(bean.getName());
            }

            PublicRoundDialog roundDialog = new PublicRoundDialog(this, "提示", list, (pos, menu) -> {
                clear(data.get(pos));
            });
            roundDialog.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void clear(BatchClearListBean bean) {
        showConfirmDialog("提示", "删除后无法恢复，请慎重操作", "确定", () -> {
            if (type == 2) {
                clearChat(bean);
            } else {
                mPresenter.batchClear(BatchClearActivity.this, bean.getCancel_id());
            }
        });
    }

    /**
     * 清除聊天记录
     */
    private void clearChat(BatchClearListBean bean) {
        showLoading();
        thread = new Thread(() -> clearChatMsg(bean));
        thread.start();
    }

    private void clearChatMsg(BatchClearListBean bean) {
        List<EMConversation> conversationList = ChatUtil.getInstance().loadConversationList();
        for (EMConversation conversation : conversationList) {
            // 这里等于1表示清除所有的聊天记录，就不用根据时间查询了
            if (bean.getDuration() == 1) {
                conversation.clearAllMessages();
            } else {
                long endTime = System.currentTimeMillis() - (1000 * 60 * 60 * 24 * bean.getDuration());
                List<EMMessage> list = conversation.searchMsgFromDB(0, endTime, Integer.MAX_VALUE);
                for (EMMessage message : list) {
                    conversation.removeMessage(message.getMsgId());
                }
            }
        }
        handler.sendEmptyMessage(0x03);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x03) {
                EventBus.getDefault().post(new ChatListRefreshEvent());
                hideLoading();
                showError("清除成功");
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        thread = null;
        if (handler != null) {
            handler.removeMessages(0x03);
            handler = null;
        }
    }
}
